package com.aquan.map_jetpack.ui.components.map_component

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.activity.compose.BackHandler
import androidx.annotation.NonNull
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.LinearScale
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.aquan.map_jetpack.R
import com.aquan.map_jetpack.ui.components.bottom.BottomContent
import com.mapbox.android.gestures.MoveGestureDetector
import com.mapbox.android.gestures.RotateGestureDetector
import com.mapbox.android.gestures.StandardScaleGestureDetector
import com.mapbox.bindgen.Expected
import com.mapbox.geojson.Feature
import com.mapbox.maps.*
import com.mapbox.maps.extension.style.StyleContract
import com.mapbox.maps.extension.style.expressions.dsl.generated.zoom
import com.mapbox.maps.extension.style.layers.addLayer
import com.mapbox.maps.extension.style.layers.generated.LineLayer
import com.mapbox.maps.extension.style.layers.generated.RasterLayer
import com.mapbox.maps.extension.style.layers.generated.lineLayer
import com.mapbox.maps.extension.style.layers.getLayer
import com.mapbox.maps.extension.style.layers.getLayerAs
import com.mapbox.maps.extension.style.layers.properties.generated.LineCap
import com.mapbox.maps.extension.style.layers.properties.generated.LineJoin
import com.mapbox.maps.extension.style.layers.properties.generated.Visibility
import com.mapbox.maps.extension.style.sources.addSource
import com.mapbox.maps.extension.style.sources.generated.geoJsonSource
import com.mapbox.maps.extension.style.sources.generated.rasterSource
import com.mapbox.maps.extension.style.style
import com.mapbox.maps.plugin.Plugin
import com.mapbox.maps.plugin.animation.camera
import com.mapbox.maps.plugin.attribution.attribution
import com.mapbox.maps.plugin.compass.compass
import com.mapbox.maps.plugin.gestures.*
import com.mapbox.maps.plugin.locationcomponent.LocationComponentPlugin
import com.mapbox.maps.plugin.logo.logo
import com.mapbox.maps.plugin.scalebar.ScaleBarPlugin
import com.mapbox.maps.plugin.scalebar.scalebar
import kotlinx.coroutines.launch
import java.lang.Exception


@SuppressLint("InflateParams")
@OptIn(MapboxExperimental::class, androidx.compose.material.ExperimentalMaterialApi::class)
@Composable
fun MapViewWidget(context: Context = LocalContext.current) {

    val list = ArrayList<String>()
//    list.add("https://gl.aibravi.com/maps/vt?lyrs=y&gl=cn&x={x}&y={y}&z={z}")
    list.add("http://47.107.31.58:8080/geoserver/csjt/wms?service=WMS&version=1.1.0&request=GetMap&layers=csjt:csxy&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png&TRANSPARENT=TRUE")

    val geoServerUrl = "http://47.107.31.58:8080/geoserver/csjt/ows"


    val listGeo = listOf(
        LineObj(
            id = "nationalrdway",
            name = "国道",
            type = "line",
            tabName = "csjt:nationalrdway",
            lineColor = "#F7455D",
            lineWidth = 4.0,
            zoom = 8.0
        ),
        LineObj(
            id = "freeway",
            name = "高速",
            type = "line",
            tabName = "csjt:freeway",
            lineColor = "#00aaff",
            lineWidth = 4.0,
            zoom = 8.0
        ),
        LineObj(
            id = "dartway",
            name = "省道",
            type = "line",
            tabName = "csjt:dartway",
            lineColor = "#00ff00",
            lineWidth = 2.0,
            zoom = 9.0
        ),
        LineObj(
            id = "countyway",
            name = "县道",
            type = "line",
            tabName = "csjt:countyway",
            lineColor = "#aaaaff",
            lineWidth = 1.0,
            zoom = 10.0
        ),
        LineObj(
            id = "countryway",
            name = "乡道",
            type = "line",
            tabName = "csjt:countryway",
            lineColor = "#ffaa7f",
            lineWidth = 0.50,
            zoom = 11.0
        ),
        LineObj(
            id = "villageway",
            name = "村道",
            type = "line",
            tabName = "csjt:villageway",
            lineColor = "pink",
            lineWidth = 0.10,
            zoom = 12.0
        ),
    )

    val featureList = listOf(
        "nationalrdway",
        "freeway",
        "dartway",
        "countyway",
        "countryway",
        "villageway",
    )


    var zoom by remember {
        mutableStateOf("8.0")
    }

    var lngLat by remember {
        mutableStateOf("${R.string.lng},${R.string.lat}")
    }


    val mapbox: MapView by remember {
        mutableStateOf(
            (LayoutInflater.from(context).inflate(R.layout.map, null, false)
                .findViewById(R.id.mapView) as MapView)
        )
    }


    LaunchedEffect(Unit) {

    }

    // 卸载当前
    DisposableEffect(Unit) {
        onDispose {
//           mapbox.removeOnMapLoadedListener {
//
//           }
        }
    }


//    var mapBox: MapboxMap? = null

    // 加载图层
    fun loadLayers(mapBoxMap: MapboxMap) {
        mapBoxMap.getStyle {

            val res = rasterSource("terrain-data") {
                tiles(value = list)
            }
            // mapbox.country-boundaries-v1
            it.addSource(source = res)
            val rasterLayer = RasterLayer("raster", "terrain-data")
            // TODO 图层添加
            it.addLayer(rasterLayer)

            var i = 0
            // TODO 添加控制
//                http://47.107.31.58:8080/geoserver/csjt/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=csjt%3Avillageway&maxFeatures=50&outputFormat=application%2Fjson
            for (item: LineObj in listGeo) {
                val geoJson = geoJsonSource(item.id) {
//                    url("http://47.107.31.58:8002/data/from_crema_to_council_crest.geojson")
                    url("$geoServerUrl?service=WFS&version=1.0.0&request=GetFeature&typeName=${item.tabName}&maxFeatures=10000&outputFormat=application%2Fjson")
                }
                val geoLayer = lineLayer(item.id, item.id) {
                    lineCap(LineCap.ROUND)
                    lineJoin(LineJoin.ROUND)
                    lineOpacity(1.0)
                    lineWidth(item.lineWidth)
                    lineColor(item.lineColor)
                    minZoom(item.zoom)
                    maxZoom(20.0)
                }

                it.addSource(source = geoJson)
                listGeo[i].geoLayer = geoLayer
                i += 1
                it.addLayer(geoLayer)
//
//                val layer = it.getLayerAs<FillLayer>(item.id)
//
//                Log.i("=====", layer.toString())
//            val mapText = it.getLayer("country-label-lg")
//
//            // Update layer properties
//                layer?.fillOpacity(0.0)
//                layer?.visibility(visibility = Visibility.NONE)
            }
        }
    }


    // TODO 处理图层不同级别的绘制
    fun loadLayersForZoom(mapboxMap: MapboxMap, zoom: Double) {

        mapboxMap.getStyle {

            for (item: LineObj in listGeo) {
                try {


                    val layer = it.getLayerAs<LineLayer>(item.id)

                    if (zoom >= item.zoom) {
                        Log.i("layers", layer.toString())
                        if (layer == null && (item.geoLayer !== null)) {
                            it.addLayer(item.geoLayer as StyleContract.StyleLayerExtension)
                        } else {
//                        val layers = it.getLayerAs<LineLayer>(item.id)
                            layer?.lineWidth(item.lineWidth + (zoom - 10.0))
                            layer?.visibility(visibility = Visibility.VISIBLE)
//                        layer.visibility
                        }
                    } else {
                        layer?.visibility(visibility = Visibility.NONE)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            // 级别大于8 的时候隐藏边界
//            val layer = it.getLayer("raster")
//            if (layer != null && zoom > 8.0) {
//                layer.visibility(visibility = Visibility.VISIBLE)
//            } else {
//                layer?.visibility(visibility = Visibility.NONE)
//            }

        }
    }

    // 弹出
    val state = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
    ///
    val scope = rememberCoroutineScope()

    ModalBottomSheetLayout(

        sheetContent = {
            BottomContent()
        },
        sheetState = state
    ) {

        Box {
            Box(modifier = Modifier.fillMaxSize()) {
                AndroidView(factory = {
                    mapbox.apply {
                        val mapBoxMap = this.getMapboxMap()
//                        mapBox = mapBoxMap
                        // 手势开关
                        this.gestures.rotateEnabled = true
                        this.gestures.scrollEnabled = true
                        this.gestures.pitchEnabled = true
                        this.gestures.quickZoomEnabled = true

                        // 隐藏logo
                        this.logo.enabled = false
                        this.attribution.enabled = false
                        this.compass.enabled = false

                        // 放大缩小按钮
                        //  this.scalebar.enabled = true

//                    this.location2.enabled = true


                        val scaleBarPlugin: ScaleBarPlugin? =
                            this.getPlugin(Plugin.MAPBOX_SCALEBAR_PLUGIN_ID)
                        // 隐藏 比例尺
                        scaleBarPlugin?.enabled = false


                        val locationPlugin: LocationComponentPlugin? =
                            this.getPlugin(Plugin.MAPBOX_LOCATION_COMPONENT_PLUGIN_ID)

                        locationPlugin.apply {
                            this?.enabled = true
                            this?.pulsingEnabled = true
                        }


//            mapBoxMap.loadStyleUri(Style.SATELLITE_STREETS)
//            mapBoxMap.loadStyleUri("mapbox://styles/yvhuem78/cl2yjhyab001d15p8ip7gbaql")
//            pk.eyJ1IjoieXZodWVtNzgiLCJhIjoiY2t6bnc1dXB2Mmh1NzJ2cXI4dGJnMnZpciJ9.2C8IA5I6d7omZUBboLakWg
//            mapbox://styles/yvhuem78/cl2yjhyab001d15p8ip7gbaql


                        this.getMapboxMap().loadStyle(
                            style("mapbox://styles/yvhuem78/cl2yjhyab001d15p8ip7gbaql") {

                            }
                        )

                        // TODO 加载图层
                        loadLayers(mapBoxMap)


//            mapBoxMap.addOnSourceAddedListener(onSourceAddedListener = {
//                Log.i("+++++", "图层加载" + it.id)
//            })

                        mapBoxMap.addOnMapClickListener { point ->
                            Log.i("用户点击", point.latitude().toString())
                            Log.i("用户点击", point.toJson().toString())



                            mapBoxMap.queryRenderedFeatures(
                                RenderedQueryGeometry(mapBoxMap.pixelForCoordinate(point)),
                                // RenderedQueryGeometry(mapBoxMap.pixelsForCoordinates()),
                                RenderedQueryOptions(featureList, null)
                            ) {
                                onFeatureClicked(it) { feature ->

                                    Log.i("用户点击", feature.properties().toString())

                                    scope.launch {
                                        state.show()
                                    }
                                    if (feature.id() != null) {
                                        viewAnnotationManager.getViewAnnotationByFeatureId(feature.id()!!)
                                            ?.toggleViewVisibility()
                                    }
                                }
                            }


                            true
                        }


                        // 监听旋转
                        val rotateListener = object : OnRotateListener {
                            override fun onRotateBegin(@NonNull detector: RotateGestureDetector) {
                                // Do something when the user starts rotating the map.
                            }

                            override fun onRotate(@NonNull detector: RotateGestureDetector) {
                                // Do something while the user rotates the map.
                            }

                            override fun onRotateEnd(@NonNull detector: RotateGestureDetector) {
                                // Do something when the user stops rotating the map.
                            }
                        }

                        // 移动地图的函数监听
                        val moveListener = object : OnMoveListener {
                            override fun onMove(detector: MoveGestureDetector): Boolean {
                                //TODO("Not yet implemented")

                                Log.i(
                                    "=====",
                                    mapBoxMap.cameraState.center.coordinates().toString()
                                )
                                val value: List<Double> = mapBoxMap.cameraState.center.coordinates()
                                lngLat = "${"%.8f".format(value[0])},${"%.8f".format(value[1])}"


                                return false
                            }

                            override fun onMoveBegin(detector: MoveGestureDetector) {
                                //TODO("Not yet implemented")
                            }

                            override fun onMoveEnd(detector: MoveGestureDetector) {
                                //TODO("Not yet implemented")
                            }


                        }


                        // 监听地图缩放
                        val scaleListener = object : OnScaleListener {
                            override fun onScale(@NonNull detector: StandardScaleGestureDetector) {
                                /// TODO("Not yet implemented")
                                Log.i("=====", "界面移动缩放完成")
                                Log.i("=====", detector.scaleFactor.toString())
                                Log.i("=====", mapBoxMap.getPrefetchZoomDelta().toString())
//                    Log.i("=====", mapBoxMap)
//                            Log.i("=====", mapBoxMap.cameraState.zoom.toString())
                                Log.i(
                                    "=====",
                                    mapBoxMap.cameraState.center.coordinates().toString()
                                )

                                val zoomVal: Double = mapBoxMap.cameraState.zoom

                                zoom = "%.1f".format(zoomVal)


                                // 处理一个图层显示与绘制
//                                loadLayersForZoom(mapboxMap = mapBoxMap, zoom = zoomVal)

                            }

                            override fun onScaleBegin(@NonNull detector: StandardScaleGestureDetector) {
                                /// TODO("Not yet implemented")
                                Log.i("=====", "界面移动缩放开始")
                            }

                            override fun onScaleEnd(@NonNull detector: StandardScaleGestureDetector) {
                                /// TODO("Not yet implemented")
                                Log.i("=====", "界面移动缩放结束")
                            }

                        }

                        // 地图加载完成的监听
                        mapBoxMap.addOnMapLoadedListener {
                            Log.i("===", "地图加载完成")
//                        mapBoxMap.addOnRotateListener(rotateListener)


                        }

                        mapBoxMap.addOnScaleListener(scaleListener)
                        mapBoxMap.addOnMoveListener(moveListener)

                        // 相机
                        mapBoxMap.addOnCameraChangeListener {
                            // Log.i("===",it.)
                        }


                    }
                })
            }

            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(bottom = 0.dp)
            ) {
                Column(
                    modifier = Modifier.fillMaxSize(),
                    verticalArrangement = Arrangement.Bottom
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(start = 0.dp)
                            .background(color = Color(0x45cccccc))
                            .height(30.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Spacer(modifier = Modifier.width(1.dp))
                        Text(text = "经纬度:", color = Color.White, fontSize = 14.sp)
                        Text(text = lngLat, color = Color.White, fontSize = 12.sp)
                        Spacer(modifier = Modifier.width(10.dp))
                        Text(text = "级别：", color = Color.White, fontSize = 14.sp)
                        Text(text = zoom, color = Color.White, fontSize = 12.sp)
                    }
                }
            }

            // 中间的指示图标
            Box(
                modifier = Modifier.fillMaxSize()

            ) {
                Column(
                    modifier = Modifier.fillMaxSize(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.center),
                        contentDescription = null,
                        modifier = Modifier
                            .height(12.dp)
                            .width(12.dp),
                        contentScale = ContentScale.None
                    )
                }

            }

//            val colorList = arrayListOf(Color(0xFF25BC6B), Color(0xFFFFCA1C))
//
//            // 地图放大缩小控件
//            Box(
//                modifier = Modifier
//                    .fillMaxSize(),
//            ) {
//                Column(
//                    modifier = Modifier
//                        .fillMaxSize()
//                        .padding(bottom = 100.dp, end = 10.dp),
//                    verticalArrangement = Arrangement.Bottom,
//                    horizontalAlignment = Alignment.End
//
//                ) {
////                    colorList
//                    Column(
//                        modifier = Modifier
//                            .height(60.dp)
//                            .width(36.dp)
//                            .background(
//                                brush = Brush.horizontalGradient(colorList),
//                                shape = RoundedCornerShape(10)
//                            ),
//                        horizontalAlignment = Alignment.CenterHorizontally,
//                        verticalArrangement = Arrangement.Center
//                    ) {
//                        Icon(
//                            imageVector = Icons.Default.Add, contentDescription = null
//                        )
//                        Divider()
//
//                        Icon(imageVector = Icons.Default.LinearScale, contentDescription = null)
//
//                    }
//                }
//            }


        }

    }

    BackHandler(
        enabled = (state.currentValue == ModalBottomSheetValue.HalfExpanded ||
                state.currentValue == ModalBottomSheetValue.Expanded),
        onBack = {
            scope.launch {
                state.hide()
            }
        })


}


data class LineObj(
    val id: String,
    val name: String,
    val type: String,
    val tabName: String,
    val lineColor: String = "red",
    val lineWidth: Double = 2.0,
    val zoom: Double = 9.0,
    var geoLayer: Any = ""

)


private fun onFeatureClicked(
    expected: Expected<String, List<QueriedFeature>>,
    onFeatureClicked: (Feature) -> Unit
) {
    Log.i("expected.isValue", expected.isValue.toString())
    if (expected.isValue && expected.value?.size!! > 0) {
        expected.value?.get(0)?.feature?.let { feature ->
            Log.i("feature", feature.toString())
            onFeatureClicked.invoke(feature)
        }
    }
}

private fun View.toggleViewVisibility() {
    visibility = if (visibility == View.VISIBLE) View.GONE else View.VISIBLE
}



